package com.feng.control.generate.entity.generator;

import java.text.MessageFormat;

import org.apache.ibatis.ibator.api.dom.java.JavaVisibility;
import org.apache.ibatis.ibator.api.dom.java.Method;
import org.apache.ibatis.ibator.api.dom.java.TopLevelClass;

import com.feng.control.generate.entity.meta.Column;
import com.feng.control.generate.entity.meta.Table;

/**
 * @author Lee
 */
public class FillDefaultValuesGenerator extends AbstractGenerator {
  public void afterEntityGenerated(TopLevelClass entityClass, Table table) {
    Method method = new Method();
    method.setName("fillDefaultValues");
    method.setVisibility(JavaVisibility.PUBLIC);
    for (Column col : table.getColumns()) {

      // 主键不生成默认值
      if (table.getPrimaryKeyColumns().contains(col)) continue;

      // 非自增且非空
      if (col.isIdentity() || !col.isMandatory()) continue;

      String type = col.getJavaType().getShortName();
      String value = "null";
      if (type.equals("String")) {
        value = "\"\"";
      } else if (type.equals("BigDecimal")) {
        value = "BigDecimal.ZERO";
      } else if (type.equals("Integer")) {
        value = "0";
      } else if (type.equals("Long")) {
        value = "0L";
      } else if (type.equals("Date")) {
        value = "new Date()";
      } else if (type.equals("Boolean")) {
        value = "false";
      } else if (col.getDomain() != null) {
        value = MessageFormat.format("{0}.values()[0]", col.getDomain().getType().getShortName());
      }
      method.addBodyLine(MessageFormat.format("if ({0} == null) {0} = {1};", col.getPropertyName(), value));
    }

    // 不是必输的直接添加到类中
    if (!method.getBodyLines().isEmpty()) {
      entityClass.addMethod(method);
    }
  }
}
